package com.syeet.gulimall.product.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author xhl
 * @date 2023/4/12
 */
@Configuration
public class ThreadPoolConfig {

    @Bean
    @Primary
    public ThreadPoolTaskExecutor threadPoolTaskExecutorExecutor(ThreadPoolConfigProperties pool) {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setThreadNamePrefix("default-thread-pool-");
        //根据电脑内核设置核心线程数
        threadPoolTaskExecutor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        //从配置文件读取参数方式
        //threadPoolTaskExecutor.setCorePoolSize(pool.getCorePoolSize());

        //设置最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 2 + 1);
        //最大线程数经过30s收缩到核心线程数
        threadPoolTaskExecutor.setKeepAliveSeconds(30);
        //设置blockqueue最大为10000，默认Integer.max_value,默认值太耗内存，不使用
        threadPoolTaskExecutor.setQueueCapacity(10000);
        threadPoolTaskExecutor.setThreadFactory(Executors.defaultThreadFactory());
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        return threadPoolTaskExecutor;
    }
}
